package com.utils.basejava.concurrent.Thread;

/**
 * 生产一个、消耗一个
 * 等待/通知范式
 * @author XR-8
 *
 */
public class ThreadCP {
	
	public static int num = 0;
	public static void main(String[] args) {
	
		Consumer consumer = new Consumer();
		Thread cs = new Thread(consumer);
		cs.start();
		
		Product product = new Product();
		Thread pd = new Thread(product);
		pd.start();

	}
}

class Product implements Runnable{

	public void run() {
		synchronized (ThreadCP.class) {
			while(true) {
				if(ThreadCP.num<=0) {
					ThreadCP.num++;
					System.out.println("生产一个"+ThreadCP.num);
					ThreadCP.class.notifyAll();
				}else {
					try {
						ThreadCP.class.wait();
					} catch (InterruptedException e) {
						e.printStackTrace();
					}
				}
			}
		}
	}
	
}

class Consumer implements Runnable{

	public void run() {
		synchronized(ThreadCP.class) {
			while(true) {
				if(ThreadCP.num>0) {
					ThreadCP.num--;
					System.out.println("消费一个"+ThreadCP.num);
					ThreadCP.class.notifyAll();
				}else {
					try {
						ThreadCP.class.wait();
					} catch (InterruptedException e) {
						e.printStackTrace();
					}
				}
			}
		}
		
	}
	
}